/**
 * 重量规则管理模块
 * 
 * 该模块负责管理重量区间计费模式下的重量区间规则配置。
 * 支持与策略关联的重量规则的增删改查操作。
 * 提供了完整的表单验证和错误处理机制。
 * 
 * 主要功能：
 * - 重量规则查询（按策略ID查询关联规则）
 * - 重量规则新增（支持重量上限和邮资设置）
 * - 重量规则编辑和更新
 * - 重量规则删除（支持删除确认）
 * - 表单验证（重量和邮资数值验证）
 * - API错误处理和用户友好的错误信息提示
 * 
 * API调用统一管理：
 * - 查询：window.FreightApp.api.getWeightRules() -> POST /weight-segment-rule/list
 * - 新增：window.FreightApp.api.addWeightRule() -> POST /weight-segment-rule/add
 * - 更新：window.FreightApp.api.updateWeightRule() -> POST /weight-segment-rule/update
 * - 删除：window.FreightApp.api.deleteWeightRule() -> POST /weight-segment-rule/delete
 * 
 * @author 运费系统团队
 * @version 2.0.0
 * @since 2025-08-29
 * @requires api.js - 统一API服务管理
 */

// 调试：检查API对象是否正确导入
console.log('API对象在weight-rules.js中:', window.FreightApp.api);

function useWeightRulesManagement() {
    const { ref, reactive } = Vue;
    // 响应式数据
    const weightRules = ref([]);
    const submitting = ref(false);
    const showAddWeightRuleModal = ref(false);
    const showEditWeightRuleModal = ref(false);
    const selectedStrategyId = ref('');
    
    const weightRuleForm = reactive({
        id: null,
        strategyId: '',
        upperBound: null,
        freight: null
    });

    /**
     * 为选中策略加载重量规则
     */
    const loadWeightRules = async () => {
        if (!selectedStrategyId.value) {
            weightRules.value = [];
            return;
        }
        
        try {
            const result = await window.FreightApp.api.getWeightRules(selectedStrategyId.value);
            if (result.code === 0) {
                // 总是更新数据，即使结果为空数组也要清除当前显示
                weightRules.value = result.data || [];
            } else {
                // API失败时清空数据
                weightRules.value = [];
                window.showMessage('加载重量规则失败: ' + result.msg, true);
            }
        } catch (err) {
            console.error('加载重量规则失败:', err);
            // 请求异常时清空数据
            weightRules.value = [];
            window.showMessage('加载重量规则失败', true);
        }
    };

    /**
     * 添加新重量规则
     */
    const addWeightRule = () => {
        if (!selectedStrategyId.value) {
            window.showMessage('请先选择策略', true);
            return;
        }
        resetWeightRuleForm();
        weightRuleForm.strategyId = selectedStrategyId.value;
        showAddWeightRuleModal.value = true;
    };

    /**
     * 编辑现有重量规则
     */
    const editWeightRule = (rule) => {
        Object.assign(weightRuleForm, rule);
        showEditWeightRuleModal.value = true;
    };

    /**
     * 提交重量规则表单
     */
    const submitWeightRule = async () => {
        const validation = validateWeightRuleForm();
        if (!validation.isValid) {
            window.showMessage(validation.errors[0], true);
            return;
        }

        submitting.value = true;
        try {
            weightRuleForm.strategyId = selectedStrategyId.value;
            
            // 更严格的API安全检查
            console.log('🔧 提交重量规则数据:', weightRuleForm);
            console.log('🔧 API对象:', window.FreightApp.api);
            console.log('🔧 API对象类型:', typeof window.FreightApp.api);
            console.log('🔧 API对象的构造函数:', window.FreightApp.api?.constructor?.name);
            
            // 检查API对象是否存在和有效
            if (!window.FreightApp.api) {
                console.error('❌ API对象为null或undefined');
                throw new Error('API对象未正确初始化，请刷新页面重试');
            }
            
            if (typeof window.FreightApp.api !== 'object') {
                console.error('❌ API不是一个对象，类型:', typeof window.FreightApp.api);
                throw new Error('API对象类型错误，请刷新页面重试');
            }
            
            // 检查API对象的post方法是否存在
            console.log('🔧 api.post存在:', !!window.FreightApp.api.post, '类型:', typeof window.FreightApp.api.post);
            if (!window.FreightApp.api.post || typeof window.FreightApp.api.post !== 'function') {
                console.error('❌ API对象缺少post方法或post不是函数');
                console.error('❌ API对象的所有属性:', Object.keys(window.FreightApp.api));
                throw new Error('API对象的post方法未正确初始化，请刷新页面重试');
            }
            
            // 安全选择API方法
            const isUpdate = Boolean(weightRuleForm.id);
            const methodName = isUpdate ? 'updateWeightRule' : 'addWeightRule';
            const apiMethod = window.FreightApp.api[methodName];
            
            console.log('🔧 选择的API方法:', methodName, '是否存在:', !!apiMethod, '类型:', typeof apiMethod);
            
            if (!apiMethod || typeof apiMethod !== 'function') {
                console.error(`❌ API方法 ${methodName} 不存在或不是函数`);
                console.error('❌ 可用的API方法:', Object.keys(window.FreightApp.api).filter(key => typeof window.FreightApp.api[key] === 'function'));
                throw new Error(`API方法 ${methodName} 不存在或不是函数，请检查api.js配置`);
            }
            
            // 参数有效性检查
            if (!weightRuleForm.strategyId) {
                console.error('❌ 策略ID为空');
                throw new Error('策略ID不能为空，请先选择策略');
            }
            
            if (!weightRuleForm.upperBound || weightRuleForm.upperBound < 0) {
                console.error('❌ 重量上限无效');
                throw new Error('重量上限不能为负数');
            }
            
            if (weightRuleForm.freight === null || weightRuleForm.freight === undefined || weightRuleForm.freight < 0) {
                console.error('❌ 邮资无效');
                throw new Error('邮资不能为空且不能为负数');
            }
            
            console.log('✅ 所有参数验证通过，准备调用API');
            
            const result = await apiMethod(weightRuleForm);
            
            console.log('🔧 API调用结果:', result);
            
            if (result && result.code === 0) {
                window.showMessage('操作成功');
                closeWeightRuleModal();
                loadWeightRules();
            } else {
                const errorMsg = result?.msg || '操作失败';
                console.warn('⚠️ API调用失败:', errorMsg);
                window.showMessage(errorMsg, true);
            }
        } catch (err) {
            console.error('❌ 重量规则提交错误详情:', err);
            console.error('❌ 错误栈信息:', err.stack);
            
            // 根据错误类型提供不同的错误信息
            let errorMessage = '提交失败';
            
            if (err.message.includes('Cannot read properties of undefined')) {
                if (err.message.includes("reading 'post'")) {
                    errorMessage = 'API对象的post方法未正确初始化，请刷新页面重试';
                } else {
                    errorMessage = 'API对象未正确初始化，请刷新页面重试';
                }
            } else if (err.message.includes('is not a function')) {
                errorMessage = 'API方法不存在，请检查系统配置';
            } else if (err.message.includes('Network Error') || err.message.includes('timeout')) {
                errorMessage = '网络连接错误，请检查网络连接后重试';
            } else if (err.message.includes('401') || err.message.includes('Unauthorized')) {
                errorMessage = '权限验证失败，请重新登录';
            } else if (err.message.includes('500')) {
                errorMessage = '服务器内部错误，请联系管理员';
            } else {
                errorMessage = err.message || '未知错误';
            }
            
            window.showMessage(`提交失败: ${errorMessage}`, true);
        } finally {
            submitting.value = false;
        }
    };

    /**
     * 删除重量规则
     */
    const deleteWeightRule = async (id) => {
        if (!confirm('确定要删除这个规则吗？')) return;

        try {
            console.log('删除重量规则 ID:', id);
            console.log('API对象:', window.FreightApp.api);
            
            const result = await window.FreightApp.api.deleteWeightRule(id);
            console.log('删除结果:', result);
            
            if (result.code === 0) {
                window.showMessage('删除成功');
                loadWeightRules();
            } else {
                window.showMessage(result.msg || '删除失败', true);
            }
        } catch (err) {
            console.error('删除重量规则错误详情:', err);
            window.showMessage('删除失败: ' + (err.message || '未知错误'), true);
        }
    };

    /**
     * 关闭重量规则模态框
     */
    const closeWeightRuleModal = () => {
        showAddWeightRuleModal.value = false;
        showEditWeightRuleModal.value = false;
        resetWeightRuleForm();
    };

    /**
     * 重置重量规则表单
     */
    const resetWeightRuleForm = () => {
        Object.assign(weightRuleForm, {
            id: null,
            strategyId: '',
            upperBound: null,
            freight: null
        });
    };

    /**
     * 验证重量规则表单
     */
    const validateWeightRuleForm = () => {
        const errors = [];
        
        if (!weightRuleForm.upperBound || weightRuleForm.upperBound < 0) {
            errors.push('重量上限不能为负数');
        }
        
        if (weightRuleForm.freight === null || weightRuleForm.freight === undefined || weightRuleForm.freight < 0) {
            errors.push('邮资不能为空且不能为负数');
        }
        
        // 检查重复的重量上限
        if (!weightRuleForm.id) {
            const existingRule = (weightRules.value || []).find(rule => 
                rule.upperBound === weightRuleForm.upperBound
            );
            if (existingRule) {
                errors.push('重量上限已存在');
            }
        } else {
            const existingRule = (weightRules.value || []).find(rule => 
                rule.upperBound === weightRuleForm.upperBound && 
                rule.id !== weightRuleForm.id
            );
            if (existingRule) {
                errors.push('重量上限已存在');
            }
        }

        return {
            isValid: errors.length === 0,
            errors
        };
    };

    /**
     * 按重量上限排序重量规则
     */
    const sortedWeightRules = () => {
        return [...(weightRules.value || [])].sort((a, b) => a.upperBound - b.upperBound);
    };

    /**
     * 验证重量规则重叠
     */
    const validateWeightRuleOverlap = (upperBound, excludeId = null) => {
        const conflicts = (weightRules.value || []).filter(rule => {
            if (excludeId && rule.id === excludeId) return false;
            
            // 检查新的重量上限是否与现有规则重叠
            // 这是一个简化的检查 - 您可能需要更复杂的逻辑
            return rule.upperBound === upperBound;
        });
        
        return conflicts.length === 0;
    };

    /**
     * 根据ID获取重量规则
     */
    const getWeightRuleById = (ruleId) => {
        return (weightRules.value || []).find(rule => rule.id === ruleId);
    };

    /**
     * 计算规则总数
     */
    const getTotalRulesCount = () => {
        return (weightRules.value || []).length;
    };

    /**
     * 获取规则摘要
     */
    const getRulesSummary = () => {
        if ((weightRules.value || []).length === 0) {
            return '暂无规则';
        }
        
        const sorted = sortedWeightRules();
        const minWeight = sorted[0]?.upperBound || 0;
        const maxWeight = sorted[sorted.length - 1]?.upperBound || 0;
        
        return `共${(weightRules.value || []).length}个规则，重量范围：0-${maxWeight}kg`;
    };

    /**
     * 批量删除重量规则
     */
    const bulkDeleteWeightRules = async (ruleIds) => {
        if (!ruleIds || ruleIds.length === 0) {
            window.showMessage('请选择要删除的规则', true);
            return;
        }
        
        if (!confirm(`确定要删除选中的${ruleIds.length}个规则吗？`)) return;
        
        try {
            let successCount = 0;
            const errors = [];
            
            for (const ruleId of ruleIds) {
                try {
                    const result = await window.FreightApp.api.deleteWeightRule(ruleId);
                    if (result.code === 0) {
                        successCount++;
                    } else {
                        errors.push(`删除规则${ruleId}失败：${result.msg}`);
                    }
                } catch (err) {
                    errors.push(`删除规则${ruleId}失败：${err.message}`);
                }
            }
            
            if (successCount > 0) {
                window.showMessage(`成功删除${successCount}个规则`);
                loadWeightRules();
            }
            
            if (errors.length > 0) {
                window.showMessage(`部分删除失败：${errors.join('；')}`, true);
            }
        } catch (err) {
            window.showMessage(err.message, true);
        }
    };

    return {
        // State
        weightRules,
        submitting,
        showAddWeightRuleModal,
        showEditWeightRuleModal,
        selectedStrategyId,
        weightRuleForm,
        
        // Methods
        loadWeightRules,
        addWeightRule,
        editWeightRule,
        submitWeightRule,
        deleteWeightRule,
        closeWeightRuleModal,
        resetWeightRuleForm,
        validateWeightRuleForm,
        sortedWeightRules,
        validateWeightRuleOverlap,
        getWeightRuleById,
        getTotalRulesCount,
        getRulesSummary,
        bulkDeleteWeightRules
    };
}
